package com.android.volley.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 */
public class IOUtil {

    public static void writeInt(OutputStream out , int i) throws IOException {
        byte[] buffer = new byte[4];

        buffer[0] = (byte) ((i >>> 24) & 0xff);
        buffer[1] = (byte) ((i >>> 16) & 0xff);
        buffer[2] = (byte) ((i >>>  8) & 0xff);
        buffer[3] = (byte)  (i         & 0xff);
        out.write(buffer);
    }

    public static byte[] wrapInt(int i){
        byte[] buffer = new byte[4];
        buffer[0] = (byte) ((i >>> 24) & 0xff);
        buffer[1] = (byte) ((i >>> 16) & 0xff);
        buffer[2] = (byte) ((i >>>  8) & 0xff);
        buffer[3] = (byte)  (i         & 0xff);

        return buffer;
    }

    public static int readInt(InputStream in) throws IOException{
        byte[] buffer = new byte[4];
        in.read(buffer);
        return  (buffer[0] & 0xff) << 24
                |   (buffer[1] & 0xff) << 16
                |   (buffer[2] & 0xff) <<  8
                |   (buffer[3] & 0xff);
    }

    public static byte[] read(InputStream in, int totalLength) throws IOException{
        byte[] bytes = new byte[totalLength];
        int readedLength = 0;
        int length = 0;
        byte[] temp = new byte[1024 * 4];

        while ((length = in.read(temp)) != -1) {
            System.arraycopy(temp, 0, bytes, readedLength, length);
            readedLength += length;
            if (readedLength == totalLength) {
                break;
            }
        }

        return bytes;
    }
}